// components/calendar/calendar.js
Component({
  properties: {
    // 初始年月，格式为"YYYY-MM"
    initDate: {
      type: String,
      value: ''
    },
    // 日期内容数据 {日期: 内容}
    dateContents: {
      type: Object,
      value: {}
    }
  },

  data: {
    year: 0,      // 当前年份
    month: 0,     // 当前月份（1-12）
    days: [],     // 当前月显示的日期数组
    weekdays: ['日', '一', '二', '三', '四', '五', '六']
  },

  methods: {
    // 初始化日历
    initCalendar(year, month) {
      // 计算当月第一天是星期几
      const firstDay = new Date(year, month - 1, 1).getDay();
      // 计算当月有多少天
      const daysInMonth = new Date(year, month, 0).getDate();
      // 计算上个月最后一天（用于填充前面空白）
      const prevMonthLastDay = new Date(year, month - 1, 0).getDate();

      const days = [];

      // 填充上个月末尾的几天
      for (let i = prevMonthLastDay - firstDay + 1; i <= prevMonthLastDay; i++) {
        days.push({
          day: i,
          isCurrentMonth: false,
          date: `${year}-${month - 1}-${i}`
        });
      }

      // 填充当月日期
      const today = new Date();
      for (let i = 1; i <= daysInMonth; i++) {
        const dateStr = `${year}-${month}-${i}`;
        days.push({
          day: i,
          isCurrentMonth: true,
          isToday: today.getFullYear() === year && 
                   today.getMonth() + 1 === month && 
                   today.getDate() === i,
          date: dateStr,
          content: this.data.dateContents[dateStr] || '' // 添加日期内容
        });
      }

      // 填充下个月开始的几天（凑满6行）
      const nextMonthDays = 42 - days.length; // 6行7列共42格
      for (let i = 1; i <= nextMonthDays; i++) {
        days.push({
          day: i,
          isCurrentMonth: false,
          date: `${year}-${month + 1}-${i}`
        });
      }

      this.setData({
        year,
        month,
        days
      });
    },

    // 上个月
    previousMonth() {
      let year = this.data.year;
      let month = this.data.month - 1;
      if (month === 0) {
        month = 12;
        year--;
      }
      this.initCalendar(year, month);
    },

    // 下个月
    nextMonth() {
      let year = this.data.year;
      let month = this.data.month + 1;
      if (month === 13) {
        month = 1;
        year++;
      }
      this.initCalendar(year, month);
    },

    // 点击日期
    onDayTap(e) {
      const date = e.currentTarget.dataset.date;
      this.triggerEvent('dateSelect', { date });
    }
  },

  lifetimes: {
    attached() {
      // 初始化：如果没有初始日期，则使用当前日期
      const today = new Date();
      let year = today.getFullYear();
      let month = today.getMonth() + 1;

      // 如果有传入的初始日期
      if (this.properties.initDate) {
        const [y, m] = this.properties.initDate.split('-').map(Number);
        year = y;
        month = m;
      }

      // 初始化日历
      this.initCalendar(year, month);
    }
  }
});